package com.powergisol.gis.handler;

import com.alibaba.fastjson.JSON;
import com.powergisol.gis.model.RASUtils;
import com.powergisol.gis.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * Created By marc
 * Date: 2020/4/21  19:02
 * Description:
 */
@Configuration
public class PasswordFilter implements Filter {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        ChangeRequestWrapper changeRequestWrapper = new ChangeRequestWrapper(httpRequest);

        Map<String, String[]> parameterMap = new HashMap<>(changeRequestWrapper.getParameterMap());
        // 获取url
        String url = httpRequest.getRequestURI();
        if(url.indexOf("/oauth/token")>=0) {
           if(null != httpRequest.getParameter("token")){
               filterChain.doFilter(changeRequestWrapper, servletResponse);
               return;
           }
            String password = httpRequest.getParameter("password");
            String randomStr = httpRequest.getParameter("randomStr");
            //将前端密码解密
            if (!redisTemplate.hasKey("privateKey"+randomStr)) {
                printJson(httpRequest,httpResponse, -1,"请刷新后重新登录");
                return ;
            }
            Object privateKey = redisTemplate.opsForValue().get("privateKey"+randomStr);
            //私钥解密(私钥对象，私钥加密串)。私钥加密串转byte,不是解密不成功或者报input too large for RSA cipher或Bad arguments
            byte[] passwords = RASUtils.decrypt((RSAPrivateKey) privateKey, RASUtils.hexStringToBytes(password));
            //还原密码
            password = new String(passwords).trim();
            parameterMap.put("password", password.split(","));
            changeRequestWrapper.setParameterMap(parameterMap);
            //复写 HttpServletRequestWrapper
            redisTemplate.delete("privateKey"+randomStr);
            filterChain.doFilter(changeRequestWrapper, servletResponse);
        }else{
            filterChain.doFilter(httpRequest, httpResponse);
        }


    }

    @Override
    public void destroy() {

    }

    private static void printJson(HttpServletRequest request, HttpServletResponse response, Integer code,String msg) {
        Result result = new Result(code,msg);
        String content = JSON.toJSONString(result);
        printContent(request,response, content);
    }
    private static void printContent(HttpServletRequest request, HttpServletResponse response, String content) {
        try {
            response.reset();
            response.setContentType("application/json");
            String origin = request.getHeader("Origin");
            response.setHeader("Access-Control-Allow-Origin", origin);
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Headers","Origin,Content-Type,Accept,token,X-Requested-With");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Cache-Control", "no-store");
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(content);
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
